package com.example.mychat.controller;

import com.example.mychat.model.User;
import com.example.mychat.model.UserMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController

public class UserController {
   @Autowired
   private UserMapper userMapper;

   @PostMapping("/login")
   @ResponseBody
   public User login(String username, String password,HttpServletRequest request){
       if(username.isEmpty()||password.isEmpty()){
           log.info("传入的用户名或密码为空");
       }
       //查看是否存在
       User user = userMapper.selectByName(username);
       if(user==null||!user.getPassword().equals(password)){
           log.info("登录失败");
           return new User();
       }
       //密码正确
       HttpSession session = request.getSession(true);
       session.setAttribute("User",user);
       user.setPassword("");    //给前端返回的数据中不加密码
       return user;

   }

   @PostMapping("/register")
   @ResponseBody
   public User register(String username,String password){
       User user = null;
       if(username.isEmpty()||password.isEmpty()){
           log.info("传入的用户名或密码为空");
       }
       try{
           user = new User();
           user.setUsername(username);
           user.setPassword(password);
           userMapper.insert(user);
       }catch (DuplicateKeyException e){
           user = new User();       //创表的时候设置username是unique,当出现异常的时候，代表用户名重复了
       }
       user.setPassword("");
       return user;

   }

   @GetMapping("/userInfo")
   public User getUserInfo(HttpServletRequest request){
       HttpSession session = request.getSession(false);
       if(session==null){
           log.info("用户未登录");
           return new User();
       }
       User user = (User)session.getAttribute("User");
       if(user ==null){
           log.info("用户获取失败");
       }
       return user;

   }


}
